import React, { Component } from 'react';
import { ImageBackground, ScrollView, View, Image, StatusBar, Text, TouchableOpacity, FlatList, RefreshControl, DeviceEventEmitter } from 'react-native';
import TabBarTitle from '../components/TabBarTitle';
import { TabBarImage, TabBarAnimationImage } from '../components/TabBarImage';
import Colors from '../constants/Colors';
import { statusBarHeight, titleHeight, width, unitWidth } from '../constants/AdapterUtil';
import { MyHeader } from '../components/MyHeader';
import { SubmitButton8, AddButton, ReduceButton, SubmitButton9 } from '../components/Button';
import { api_member_cart_get_list, api_member_cart_select, api_member_cart_update, api_member_cart_remove } from '../constants/HttpServices';
import { postFetch } from '../constants/HttpExtension';
import MyListView from '../components/MyListView';
import { DeleteTextView } from '../components/MyTextView';
import { CommonModal2, ChangeCountModal } from '../components/Modal';
import { show } from '../constants/Toast';

export default class BuyScreen extends Component {
    static navigationOptions = ({ navigation, jumpToIndex, scene }) => ({
        title: 'me',
        tabBarLabel: ({ focused }) => (
            <TabBarTitle
                focused={focused}
                title={'购物车'}
            />
        ),
        tabBarIcon: ({ focused }) => (
            <TabBarAnimationImage
                focused={focused}
                hasSelect={require('../res/ic_buy_c.png')}
                noSelect={require('../res/ic_buy_n.png')}
            />
        ),
        tabBarOnPress: (options) => {
            DeviceEventEmitter.emit('tabClick', '');
            options.defaultHandler();
        },
        tabBarOnLongPress: (options) => {
            return
        },
    });

    constructor(props) {
        super(props)
        this.state = {
            userInfo: {},
            list: [],
            chooseList: [],
            totalprice: '0',
            isEdit: false,
            allChoose: false,
            currentEditId: '0',
            currentEditCount: '0',
        }
    }

    componentDidMount() {
        this.props.navigation.addListener('didFocus', payload => {
            this.refs.MyListView.onRefresh();
        })
    }

    render() {
        return (
            <View style={{ flex: 1, backgroundColor: Colors.colorF7 }}>
                <MyHeader title='购物车' righttext={this.state.isEdit ? '完成' : '管理'} rightClick={() => {
                    this.setState({
                        isEdit: !this.state.isEdit
                    })
                }} />
                <MyListView
                    style={{ marginBottom: 60 * unitWidth, }}
                    ref='MyListView'
                    list={this.state.list}
                    renderItem={this.getItem.bind(this)}
                    getList={this.getData.bind(this)}
                />
                <ImageBackground style={{
                    flexDirection: 'row', position: 'absolute', bottom: 0,
                    alignItems: 'center', width: width, height: 60 * unitWidth
                }}
                    source={require('../res/gwc_jiesaunkk.png')} resizeMode='stretch'>
                    <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center', flex: 0.8, justifyContent: 'center' }}
                        onPress={() => {
                            this.changeAll();
                        }}>
                        <Image style={{
                            width: 18 * unitWidth, height: 18 * unitWidth
                        }}
                            source={this.state.allChoose ? require('../res/gwc_gxxxx.png') : require('../res/me_wsxxyd2.png')} resizeMode='stretch' />
                        <Text style={{ fontSize: 14, color: Colors.white, marginLeft: 10 * unitWidth }}>全选</Text>
                    </TouchableOpacity>
                    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                        {this.state.isEdit ?
                            null
                            :
                            <Text style={{ fontSize: 14, color: Colors.white }}>合计:{this.state.totalprice}</Text>
                        }
                    </View>
                    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                        {this.state.isEdit ?
                            <SubmitButton9 text='删除' onPress={() => {
                                this.refs.CommonModal2.showModal();
                            }} />
                            :
                            <SubmitButton8 text='结算' onPress={() => {
                                let a = false//判断是否可以结算
                                if (this.state.list.length == 0) {
                                    show('没有可结算物品')
                                    return
                                }
                                for (let x of this.state.list) {
                                    for (let y of x.goods) {
                                        if (y.selected == '1') {
                                            a = true;
                                            break;
                                        }
                                    }
                                }
                                if (a) {
                                    this.props.navigation.navigate('ConfirmOrder')
                                } else {
                                    show('没有可结算物品')
                                }
                            }} />
                        }
                    </View>
                </ImageBackground>
                <CommonModal2 ref='CommonModal2' title='是否删除？' comfirmText='确认' cancelText='取消'
                    comfirmClick={() => {
                        let ids = []
                        for (let x of this.state.list) {
                            for (let y of x.goods) {
                                if (y.selected == '1') {
                                    ids.push(y.id)
                                }
                            }
                        }
                        if (ids.length == 0) {
                            show('请选择需要删除的物品')
                            return
                        }
                        this.delete(ids)
                    }} />
                <ChangeCountModal ref='ChangeCountModal' id={this.state.currentEditId} count={this.state.currentEditCount}
                    comfirmClick={(count) => {
                        this.changeSingle(this.state.currentEditId, count)
                    }} />
            </View>
        )
    }

    getItem({ item, index }) {
        return (
            <View style={{ alignItems: 'center' }}>
                <View style={{
                    width: 350 * unitWidth, minHeight: 150 * unitWidth, borderRadius: 7,
                    backgroundColor: Colors.white, marginTop: 8 * unitWidth, paddingHorizontal: 8 * unitWidth
                }}>
                    <TouchableOpacity style={{ height: 40 * unitWidth, flexDirection: 'row', alignItems: 'center' }}
                        activeOpacity={0.7} onPress={() => {
                            this.props.navigation.navigate('ServiceProviderDetail', { merchid: item.merch_id })
                        }}>
                        <TouchableOpacity activeOpacity={0.7} onPress={() => {
                            this.changeShopAll(index)
                        }}>
                            <Image style={{
                                width: 18 * unitWidth, height: 18 * unitWidth
                            }}
                                source={this.state.chooseList[index].all ? require('../res/gwc_xzq2.png') : require('../res/me_wsxxyd2.png')} resizeMode='stretch' />
                        </TouchableOpacity>
                        <Image style={{
                            width: 12 * unitWidth, height: 11 * unitWidth, marginLeft: 10 * unitWidth
                        }}
                            source={require('../res/gwc_gs.png')} resizeMode='stretch' />
                        <Text style={{ fontSize: 14, color: Colors.black, marginLeft: 5 * unitWidth }}>{item.merchname}</Text>
                        <Image style={{
                            width: 5 * unitWidth, height: 10 * unitWidth, position: 'absolute', right: 0 * unitWidth,
                        }}
                            source={require('../res/me_back.png')} resizeMode='stretch' />
                    </TouchableOpacity>
                    <View style={{ backgroundColor: Colors.colorEF, width: 350 * unitWidth, alignSelf: 'center', height: 0.5, }} />
                    <View>
                        {this.getGoodsView(item.goods, index)}
                    </View>
                </View>
            </View>
        )
    }

    getGoodsView(list, index) {
        let views = []
        for (let i = 0, len = list.length; i < len; i++) {
            let item = list[i];
            views.push(
                <View style={{ height: 109 * unitWidth, flexDirection: 'row', alignItems: 'center' }}>
                    <TouchableOpacity activeOpacity={0.7} onPress={() => {
                        this.changeItem(index, i)
                    }}>
                        <Image style={{
                            width: 18 * unitWidth, height: 18 * unitWidth
                        }}
                            source={item.selected == '1' ? require('../res/gwc_xzq2.png') : require('../res/me_wsxxyd2.png')} resizeMode='stretch' />
                    </TouchableOpacity>
                    <Image style={{
                        width: 110 * unitWidth, height: 80 * unitWidth, marginLeft: 9 * unitWidth
                    }}
                        source={{ uri: item.thumb }} resizeMode='stretch' />
                    <View style={{ marginLeft: 10 * unitWidth }}>
                        <Text style={{ color: Colors.black, fontSize: 14, marginVertical: 4 * unitWidth, width: 190 * unitWidth }}>{item.title}</Text>
                        <View style={{
                            paddingHorizontal: 7 * unitWidth, borderWidth: 0.5, marginTop: 5 * unitWidth,
                            borderColor: Colors.colorRed, borderRadius: 5, alignSelf: 'flex-start'
                        }}>
                            <Text style={{ color: Colors.colorRed, fontSize: 10, }}>线下价格:￥{item.offlineprice}</Text>
                        </View>
                        <View style={{ alignSelf: 'flex-start', marginTop: 2 * unitWidth, flexDirection: 'row', alignItems: 'center', width: 190 * unitWidth }}>
                            <Text style={{ color: Colors.colorRed, fontSize: 17, }}>￥{item.marketprice}</Text>
                            <DeleteTextView text={'￥' + item.productprice} style={{ marginLeft: 3 * unitWidth }} />
                            <View style={{ position: 'absolute', right: 0, flexDirection: 'row', alignItems: 'center', width: 50 * unitWidth, justifyContent: 'space-between' }}>
                                <ReduceButton onPress={() => {
                                    if (item.total - 1 > 0) {
                                        this.changeSingle(item.id, parseInt(item.total) - 1)
                                    }
                                }} />
                                <TouchableOpacity style={{ justifyContent: 'center', alignItems: 'center' }} onPress={() => {
                                    this.setState({
                                        currentEditId: item.id,
                                        currentEditCount: item.total
                                    }, () => {
                                        this.refs.ChangeCountModal.showModal();
                                    })
                                }}>
                                    <Text style={{ color: Colors.color99, fontSize: 14, minWidth: 30 * unitWidth, textAlign: 'center' }}>{item.total}</Text>
                                </TouchableOpacity>
                                <AddButton onPress={() => { this.changeSingle(item.id, parseInt(item.total) + 1) }} />
                            </View>
                        </View>
                    </View>
                </View>
            );
        }
        return views
    }

    changeAll() {
        this.state.allChoose = !this.state.allChoose
        // if (this.state.allChoose) {
        //     for (let i = 0, len1 = this.state.chooseList.length; i < len1; i++) {
        //         this.state.chooseList[i].all = true
        //         for (let j = 0, len2 = this.state.chooseList[i].list.length; j < len2; j++) {
        //             this.state.chooseList[i].list[j] = true;
        //         }
        //     }
        // } else {
        //     for (let i = 0, len1 = this.state.chooseList.length; i < len1; i++) {
        //         this.state.chooseList[i].all = false
        //         for (let j = 0, len2 = this.state.chooseList[i].list.length; j < len2; j++) {
        //             this.state.chooseList[i].list[j] = false;
        //         }
        //     }
        // }
        // this.setState({
        //     chooseList: this.state.chooseList
        // })

        let ids = []
        for (let x of this.state.list) {
            for (let y of x.goods) {
                ids.push(y.id)
            }
        }
        if (ids.length == 0) {
            show('购物车中无商品')
            return
        }
        if (this.state.allChoose) {
            this.changeMultiple(ids, '1')
        } else {
            this.changeMultiple(ids, '0')
        }
    }

    changeShopAll(index) {
        // let item = this.state.chooseList[index]
        // item.all = !item.all
        // if (item.all) {
        //     for (let i = 0, len = item.list.length; i < len; i++) {
        //         item.list[i] = true
        //     }
        // } else {
        //     for (let i = 0, len = item.list.length; i < len; i++) {
        //         item.list[i] = false
        //     }
        // }
        // console.log(this.state.chooseList)
        // this.setState({
        //     chooseList: this.state.chooseList
        // })

        let item = this.state.list[index]
        let ids = []
        for (let x of item.goods) {
            ids.push(x.id)
        }
        if (this.state.chooseList[index].all) {
            this.changeMultiple(ids, '0')
        } else {
            this.changeMultiple(ids, '1')
        }
    }

    changeItem(index, i) {
        // this.state.chooseList[index].list[i] = !this.state.chooseList[index].list[i]
        // this.setState({
        //     chooseList: this.state.chooseList
        // })

        let item = this.state.list[index].goods[i]
        let ids = [item.id]
        if (item.selected == '1') {
            this.changeMultiple(ids, '0')
        } else {
            this.changeMultiple(ids, '1')
        }
    }

    getData(page) {
        let params = {

        }
        postFetch(api_member_cart_get_list, params, {
            success: (response) => {
                this.createChooseList(response.result.list, page, response.result.ischeckall)
                if (page == 1) {
                    this.setState({
                        list: response.result.list,
                        totalprice: response.result.totalprice
                    }, () => {
                        this.refs.MyListView.onHasMore();
                    })
                } else {
                    if (response.result.list && response.result.list.length > 0) {
                        this.setState({
                            list: this.state.list.concat(response.result.list),
                        }, () => {
                            this.refs.MyListView.onHasMore();
                        })
                    } else {
                        this.refs.MyListView.onNoMore();
                    }
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    createChooseList(list, page) {
        if (list && list.length > 0) {
            let chooseList = []
            let allChoose = true
            for (let x of list) {
                let temp = { all: true };
                for (let y of x.goods) {
                    if (y.selected != '1') {
                        temp.all = false;
                        allChoose = false;
                        break
                    }
                }
                chooseList.push(temp)
            }
            this.state.allChoose = allChoose
            if (page == 1) {
                this.state.chooseList = chooseList
                this.setState({ chooseList: this.state.chooseList, allChoose: this.state.allChoose })
            } else {
                this.state.chooseList = [...this.state.chooseList, ...chooseList]
                this.setState({ chooseList: this.state.chooseList, allChoose: this.state.allChoose })
            }
        }
    }

    //批量修改购物车
    changeMultiple(ids, selected) {
        let idss = ''
        for (let i = 0, len = ids.length; i < len; i++) {
            if (i != len - 1) {
                idss += ids[i] + ','
            } else {
                idss += ids[i]
            }
        }
        let params = {
            ids: idss,
            selected: selected
        }
        postFetch(api_member_cart_select, params, {
            success: (response) => {
                this.refs.MyListView.onRefresh();
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //修改单个商品的数量
    changeSingle(id, total) {
        let params = {
            id: id,
            total: total
        }
        postFetch(api_member_cart_update, params, {
            success: (response) => {
                this.refs.MyListView.onRefresh();
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //删除购物车商品
    delete(ids) {
        let params = {
            ids: ids,
        }
        postFetch(api_member_cart_remove, params, {
            success: (response) => {
                this.refs.MyListView.onRefresh();
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }
}